﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using Com.ThrongIn.Utilities;
using System.Net;
using System.IO;
namespace ThrongIn
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    public class ImageHandler : IHttpHandler
    {
        
        public void ProcessRequest(HttpContext context)
        {
            Bitmap bitOutput= null;
            Bitmap bitInput = GetImage(context);        
            int width=0, height=0;
            if(Int32.TryParse(context.Request.QueryString["width"],out width) && Int32.TryParse(context.Request.QueryString["height"],out height))
            {
                bitOutput = ImageResizer.ResizeImage(bitInput, width, height, ImageResizer.ResizeOptions.MaxWidthAndHeight);
            }        
            context.Response.ContentType = "image/jpeg";
            bitOutput.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

            return;
        }


        /// <summary>
        /// Get the image requested via the query string.
        /// </summary>
        ///     /// <returns>Return the requested image or the "no image" default if it does not exist.</returns>
        public Bitmap GetImage(HttpContext context)
        {

            Bitmap bitOutput = null;
            try
            {
                WebRequest req = WebRequest.Create(HttpContext.Current.Server.MapPath(context.Request.QueryString["image"]));
                WebResponse response = req.GetResponse();
                Stream stream = response.GetResponseStream();
                bitOutput = new Bitmap(stream);
                stream.Close();
            }
            catch
            {
            }
            return bitOutput;

        }   
     

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
